package com.example.service;

import com.example.mapper.MaterialMapper;
import com.example.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MaterialService {
    @Autowired
    private MaterialMapper materialMapper;

    public List<Material> getMaterialList(ConditionsQuery conditionsQuery) {
        List<Material>list=materialMapper.getMaterialList(conditionsQuery);
        return list;
    }

    public Result addMaterial(Material material) {
        /**
         * 非空校验
         */
        if(!StringUtils.hasText(material.getTitle())){
            return new Result(100,"标题不能为空",null);
        }
        if(!StringUtils.hasText(material.getMessage())){
            return new Result(100,"内容不能为空",null);
        }

        /**
         * 是否存在
         */
        material.setCreate_time(new Date());
        material.setUpdate_time(new Date());
        int row=materialMapper.addMaterial(material);
        if(row!=1){
            return new Result(100,"操作失败",null);
        }
        return new Result(200,"操作成功",null);
    }

    public Result editMaterial(Material material) {
        /**
         * 非空校验
         */
        if(!StringUtils.hasText(material.getTitle())){
            return new Result(100,"标题不能为空",null);
        }
        if(!StringUtils.hasText(material.getMessage())){
            return new Result(100,"内容不能为空",null);
        }
        if(material.getId()==null){
            return new Result(100,"id不能为空",null);
        }
        /**
         *
         */
       // material.setCreate_time(new Date());
        material.setUpdate_time(new Date());
        int row=materialMapper.editMaterialById(material);
        if(row!=1){
            return new Result(100,"操作失败",null);
        }
        return new Result(200,"操作成功",null);
    }

    public Result delMaterialById(int id) {
        /**
         * 查询是否存在
         */
        Material m=materialMapper.getMaterialById(id);
        if(m==null){
            return new Result(100,"材料不存在",null);
        }
        /**
         * 先删除
         */
        int row =materialMapper.delMaterialById(id);

        if(row!=1){
            return new Result(100,"操作失败",null);
        }
        return new Result(200,"删除成功",null);
    }

    public Result delBatch(String ids) {
        if (!StringUtils.hasText(ids)){
            return new Result(100,"请至少选择一条记录",null);
        }

        String[] idStr =ids.split(",");

        List<Integer> idList=new ArrayList<>();

        for (int i=0; i<idStr.length;i++){
            idList.add(Integer.parseInt(idStr[i]));
        }
        int rows =materialMapper.delBatch(idList);
        if(rows!=idList.size()){
            return new Result(100,"操作失败",null);
        }
        return new Result(200,"删除成功",null);
    }
}
